<?php
// +----------------------------------------------------------------------
// | 幕小铺
// +----------------------------------------------------------------------
// | 版权所有 2016~2020 幕小铺科技（大连）有限公司
// +----------------------------------------------------------------------
// | 2020/06/02
// +----------------------------------------------------------------------

namespace app\erp\admin;

use app\admin\controller\Admin;
use think\Db;
use app\common\builder\ZBuilder;
/**
 * 调拨入库
 * @package app\cms\admin
 */
class AllocationWarehousing extends Admin
{

    /**
     * 首页
     * @author shiqiang
     * @return mixed
     */
    public function index()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);
        //获取筛选
        $map = $this->getMap();
        //数据获取
        $data = input();
		
		$uid = UID;//后台管理员ID
		$sotre_user = model('app\user\model\User') -> find($uid);//获取列表
		
		$map1 = [];
		$map2 = [];
		if($sotre_user['store_uid'] > 0){
			//根据门店id 查询出仓库的id
			$warehouse_list = model('ErpStoreWarehouse') -> getStoreWarehouse($sotre_user['store_id']);
			foreach ($warehouse_list['data'] as $key => $value) {
				if($value['type'] == 1){//分店仓库
					$store_warehouse_list[] = $value['wid'];
				}
			}
			$warehouse_id = $store_warehouse_list[0];
			$map1[] = ['from_warehouse_id', '=', $warehouse_id];
			$map2[] = ['to_warehouse_id', '=', $warehouse_id];
		}
		
		//tab
        $list_tab = [
            'tab2' => ['title' => '已出库', 'url' => url('index', ['group' => 'tab2'])],
            'tab4' => ['title' => '已入库', 'url' => url('index', ['group' => 'tab4'])],
        ];

        // 数据列表
        $group = isset($data['group']) ? $data['group'] : 'tab2';
        switch ($group) {
            case 'tab2':
                $map1[] = ['all_status', '=', 2];
                $map2[] = ['all_status', '=', 2];
                break;
			case 'tab4':
                $map1[] = ['all_status', '=', 4];
                $map2[] = ['all_status', '=', 4];
                break;
        }
		
        //数据列表
		// $map[] = ['all_status', 'in', [2,4]];
		$data_list =  model('ErpAllocation') -> whereOr([$map1, $map2]) -> order('create_time desc') -> paginate();//获取列表
		
		foreach($data_list as $key => $value){
			// $data_list[$key]['nick_name'] 		= model('user_center/Member', 'model\user') -> find($value['uid']) -> nick_name;
			$data_list[$key]['nick_name'] 		= model('app\user\model\User') -> find($value['uid']) -> nickname;
			$data_list[$key]['from_warehouse'] 	= get_nick_name('1','ErpWarehouse','id',$value['from_warehouse_id'],'title');
			$data_list[$key]['to_warehouse'] 	= get_nick_name('1','ErpWarehouse','id',$value['to_warehouse_id'],'title');
		}
		
		$btn_details = [
			'title' => '详情',
			'icon'  => 'fa fa-fw fa-key',
			'class' => 'btn btn-xs btn-default',
			'href'  => url('details', ['id' => '__id__']),
		];
		
		$btn_add = [
			'title' => '入库',
			'icon'  => 'fa fa-fw fa-key',
			'class' => 'btn btn-xs btn-default',
			'href'  => url('warehousing', ['id' => '__id__']),
			'data-title' => '确定要入库吗？'
		];
		
        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table') // 设置页面标题
			->setPageTitle('调拨单列表')
            ->setPrimaryKey('id') // 设置主键名为id
            ->setTableName('erp_goods_allocation') // 设置数据表名
            ->addColumns([ // 批量添加列
                ['nick_name', '操作人'],
                ['from_warehouse', '调出仓'],
                ['to_warehouse', '调入仓'],
                ['code', '调拨单号'],
                ['remark', '备注'],
                ['handled_by', '经办人'],
                ['all_status', '调拨状态', 'status' , '', [0 => '申请中:warning', 2 => '已出库:success', 3 => '取消出库:default', 4 => '已入库:info']],//0申请中 1已审核 2已出库 3取消出库 4已入库
                ['create_time', '创建时间', 'datetime'],
                ['right_button', '操作', 'btn']
            ])
			->setSearchArea([
				['text', 'code', '调拨单号', 'like'],
                ['text', 'handled_by', '经办人', 'like'],
				['select', 'all_status', '调拨单状态', '', '', [2 => '已出库', 4 => '已入库']],
				['daterange', 'create_time', '创建时间'],
            ])
			->addRightButton('btn_add', $btn_add, true) // 批量添加右侧按钮
            ->addRightButton('custom', $btn_details, true) // 批量添加右侧按钮
			->replaceRightButton(['all_status' => 4], '', ['btn_add'])
			->setTabNav($list_tab, $group)
            ->setRowList($data_list) // 设置表格数据
            ->fetch(); // 渲染页面

    }
	
	//调拨单详情
	public function details($id = []){
		$info = model('ErpAllocation') -> find($id);
		
		switch ($info['all_status']) {
			case 0;
				$data['all_status'] = '申请中';
				break;
			case 1;
				$data['all_status'] = '已审核';
				break;
			case 2;
				$data['all_status'] = '已出库';
				break;
			case 3;
				$data['all_status'] = '取消出库';
				break;
			case 4;
				$data['all_status'] = '已入库';
				break;
		}
		
		$table_data = [
			['sku_id', '调拨商品', '调拨申请数量', '实际出库数量', '出库备注', '实际入库数量', '入库备注'],
		];
		
		$info['nick_name'] 		= model('app\user\model\User') -> find($info['uid']) -> nickname;
		$info['from_warehouse'] = get_nick_name('1','ErpWarehouse','id',$info['from_warehouse_id'],'title');
		$info['to_warehouse'] 	= get_nick_name('1','ErpWarehouse','id',$info['to_warehouse_id'],'title');
		
		$allocation_sku = model('ErpAllocationSku') -> where('allocation_id', $id) -> column('sku_id,num,ck_num,rk_num,ck_remark,rk_remark');
		foreach($allocation_sku as $key => $value){
			$goods_info = model('ErpGoodsSku') -> find($key);
			if($goods_info['goods_specifications'] != ''){
				$goods_name = $goods_info['goods_name'] . ' - ' . $goods_info['goods_specifications'];
			}else{
				$goods_name = $goods_info['goods_name'];
			}
			
			$table_data[] = [$key, $goods_name, $value['num'], $value['ck_num'], $value['ck_remark'], $value['rk_num'], $value['rk_remark']];
		}
		
		$ware_info = model('ErpGoodsWarehousing') -> where('code', $info['code']) -> find();
		
		$info['ck_remark'] 		= $ware_info['remark'];
		$info['ck_handled_by'] 	= $ware_info['handled_by'];
		$info['rk_remark'] 		= $ware_info['rk_remark'];
		$info['rk_handled_by'] 	= $ware_info['rk_handled_by'];
		//批量审核最多允许20个
		return ZBuilder::make('form')
            ->setPageTitle('采购单详情') // 设置页面标题
            ->addFormItems([ // 批量添加表单项
				['text', 'nick_name', '调拨申请人', '', '', '', 'readonly="readonlys"'],
				['text', 'code', '调拨单号', '', '', '', 'readonly="readonlys"'],
				['text', 'from_warehouse', '调出仓', '', '', '', 'readonly="readonlys"'],
				['text', 'to_warehouse', '调入仓', '', '', '', 'readonly="readonlys"'],
				['text', 'remark', '调拨备注', '', '', '', 'readonly="readonlys"'],
				['text', 'handled_by', '调拨经办人', '', '', '', 'readonly="readonlys"'],
				['text', 'ck_remark', '出库备注', '', '', '', 'readonly="readonlys"'],
				['text', 'ck_handled_by', '出库经办人', '', '', '', 'readonly="readonlys"'],
				['complexTable', 'list_user', '调拨单sku', $table_data],
				['text', 'rk_remark', '入库备注', '', '', '', 'readonly="readonlys"'],
				['text', 'rk_handled_by', '入库经办人', '', '', '', 'readonly="readonlys"'],
			])
			->hideBtn(['submit', 'back'])
			->setFormData($info) // 设置表单数据
            ->fetch();
	}
	
	/**
     * 入库
     * @author  shiqiang
     * @return mixed
     * @throws \think\Exception
     */
	public function warehousing($id = ''){
		DB::startTrans();//启动事务
		
		if ($this->request->isPost()) {
            //数据接收
            $data = $this->request->post('', null, 'trim');
			
			$rk_remark      = isset($data['rk_remark']) ? $data['rk_remark'] : '';
            $rk_handled_by  = isset($data['rk_handled_by']) ? $data['rk_handled_by'] : '';
			if($rk_handled_by == '') $this->error('请输入调拨入库经办人');
			
			unset($data['__token__']);
			unset($data['nick_name']);
			unset($data['from_warehouse']);
			unset($data['to_warehouse']);
			unset($data['code']);
			unset($data['remark']);
			unset($data['handled_by']);
			unset($data['ck_remark']);
			unset($data['ck_handled_by']);
			unset($data['rk_remark']);
			unset($data['rk_handled_by']);
			
			//校验采购单
			$order_code = model('ErpAllocation') -> find($id);
			if(empty($order_code) || $order_code['all_status'] != 2){
				DB::rollback();
			    $this->error('调拨单已失效，请检查调拨单');
			}
			
			//调拨出库操作 - 插入操作记录
			$code 			= $order_code['code'];
			$warehouse_id 	= $order_code['to_warehouse_id'];//仓库id
			$w_id = model('ErpGoodsWarehousing', 'model') -> where('code', $order_code['code']) -> find() -> id;
			$rel = model('ErpGoodsWarehousing', 'model') -> editData($w_id, $rk_handled_by, $rk_remark);
			if($rel['code'] < 0){
				DB::rollback();
				$this->error($rel['message']);
			}
			//组合数据
			$sku_arr = [];
			
			
			foreach($data as $key => $value){
				$sku_info = explode('/', $key);
				$sku_id   = $sku_info[1]; //商品skuid
				
				$map = [];
				$map['allocation_id'] = $id;
				$map['sku_id'] 		  = $sku_id;
				$purchase_sku = model('ErpAllocationSku') -> where($map) -> find();
				//组合sku信息
				$sku_arr[$sku_id]['id'] 	= $purchase_sku['id'];
				$sku_arr[$sku_id]['sku_id'] = $sku_id;
				
				if($sku_info[0] == 'rk_num'){
					if($value == ''){
						DB::rollback();
						$this->error('请输入商品入库数量！');
					} 
					if($value > $purchase_sku['ck_num']){
						DB::rollback();
						$this->error('入库数量不能大于出库数量！');
					}
					$sku_arr[$sku_id]['rk_num'] = $value;
				}
				
				if($sku_info[0] == 'remark'){
					$sku_arr[$sku_id]['rk_remark'] = $value;
				}	
			}
			//插入实际出库数量
			$rel = model('ErpAllocationSku') -> saveAll($sku_arr);//dump($rel);
			if(!$rel){
				DB::rollback();
				$this->error('插入失败，请重试');
			}
			//入库 更新库存
			$rel = model('ErpAllocation') -> editDataOutGoing($id,'4');
			if($rel['code'] == 200){
				$rel = model('ErpAllocation') -> warehousing($id);//调入仓 入库 增加库存
				if($rel['code'] < 0){
					$this->error($rel['message']);
				}
				
				DB::commit();
				$this->success('入库成功', cookie('__forward__'), '_parent_reload');
			}else{
				$this->error($rel['message']);
			}
		}
		
		$goods_sku_id = model('ErpAllocationSku') -> where('allocation_id', $id) -> column('sku_id,num,ck_num,ck_remark');
		$table_data = [
			['调拨商品', '调拨申请数量', '实际出库数量', '出库备注', '实际入库数量', '备注'],
		];
		foreach($goods_sku_id as $key => $value){
			$sku_info = model('ErpGoodsSku') -> find($key);
			if($sku_info['goods_specifications'] != ''){
				$goods_name = $sku_info['goods_name'] . ' - ' . $sku_info['goods_specifications'];
			}else{
				$goods_name = $sku_info['goods_name'];
			}
			$table_data[] = [$goods_name, $value['num'], $value['ck_num'], $value['ck_remark'], '<input type="text" name="rk_num/'. $sku_info['id'] .'" />', '<input type="text" name="remark/'. $sku_info['id'] .'" />'];
		}
		
		$info = model('ErpAllocation') -> find($id);
		$info['nick_name'] 		= model('app\user\model\User') -> find($info['uid']) -> nickname;
		$info['from_warehouse'] = get_nick_name('1','ErpWarehouse','id',$info['from_warehouse_id'],'title');
		$info['to_warehouse'] 	= get_nick_name('1','ErpWarehouse','id',$info['to_warehouse_id'],'title');
		
		$ware_info = model('ErpGoodsWarehousing') -> where('code', $info['code']) -> find();
		$info['ck_remark'] 		= $ware_info['remark'];
		$info['ck_handled_by'] 	= $ware_info['handled_by'];
       // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('出库单 - 出库操作') // 设置页面标题
            ->addFormItems([
				['text', 'nick_name', '出库操作人', '', '', '', 'readonly="readonlys"'],
				['text', 'from_warehouse', '调出仓', '', '', '', 'readonly="readonlys"'],
				['text', 'to_warehouse', '调入仓', '', '', '', 'readonly="readonlys"'],
				['text', 'code', '调拨单号', '', '', '', 'readonly="readonlys"'],
				['text', 'remark', '备注', '', '', '', 'readonly="readonlys"'],
				['text', 'handled_by', '采购经办人', '', '', '', 'readonly="readonlys"'],
				['text', 'ck_remark', '出库备注', '', '', '', 'readonly="readonlys"'],
				['text', 'ck_handled_by', '出库经办人', '', '', '', 'readonly="readonlys"'],
				['text', 'rk_remark', '入库备注'],
				['text', 'rk_handled_by', '入库经办人', '', get_nickname(UID)],
			])
			->setFormData($info) // 设置表单数据
			->addFormItems([ // 批量添加表单项
				['complexTable', 'list_user', '采购单sku', $table_data]
			])
            ->fetch();
	}
	 
	/* public function warehousing($id = ''){
		$rel = model('ErpAllocation') -> editDataOutGoing($id,'4');
		if($rel['code'] == 200){
			$rel = model('ErpAllocation') -> warehousing($id);//出库减库存
			if($rel['code'] < 0){
				$this->error($rel['message']);
			}
		}else{
			$this->error($rel['message']);
		}
		$this->success('出库完成', cookie('__forward__'));
	} */
}